package com.fhz.day008;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownActivity extends AppCompatActivity {

    private Button down;
    private Button readImage;
    private ImageView img;
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down);

        down = (Button) findViewById(R.id.down);
        readImage = (Button) findViewById(R.id.readImage);
        img = (ImageView) findViewById(R.id.img);


        down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyTask().execute("http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg");
            }
        });


        readImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //读
                File file = Environment.getExternalStorageDirectory();
                File file1 = new File(file, "xiaoxue.jpg");
                //BitmapFactory可以直接根据SD卡图片路径转成一个bitmap对象
                bitmap= BitmapFactory.decodeFile(file1.getAbsolutePath());
                //设置图片
                img.setImageBitmap(bitmap);
            }
        });



        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},888);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

//        for (int i = 0; i < grantResults.length; i++) {
//            if(grantResults[i] == PackageManager.PERMISSION_GRANTED){
//                //所有权限都同意了
//            }
//        }
        if(requestCode == 888 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            //从网络下载,并且存入到sd中.

        }else{
//            finish();
        }

    }

    //异步下载
    public class MyTask extends AsyncTask<String,String,String> {

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(DownActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected String doInBackground(String... strings) {
            FileOutputStream out=null;
            InputStream inputStream=null;//网络连接的输入流
            HttpURLConnection connection=null;//向SD卡写的输出流
            try {
                URL url= new URL(strings[0]);
                connection= (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5*1000);
                connection.setReadTimeout(5*1000);
                if (connection.getResponseCode()==200){
                    inputStream = connection.getInputStream();
                    //TODO 获取SD卡的路径
                    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//是否挂载
                        File file = Environment.getExternalStorageDirectory();
                        out = new FileOutputStream(new File(file,"xiaoxue.jpg"));
                        byte[] bytes = new byte[1024];
                        int len=0;
                        while((len=inputStream.read(bytes))!=-1){
                            out.write(bytes,0,len);
                        }
                        out.flush();
                    }

                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //关流
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(connection!=null){
                    connection.disconnect();
                }
            }
            return null;
        }
    }



    public void down(View view) {


    }
}